extends BTAction

func _enter() -> void:
	pass

func _tick(_delta: float) -> Status:
	var unit: Unit = agent

	
	# 优先使用单位自定义选择方法
	if unit.has_method("select_target"):
		# 调用自定义选择方法并传入候选列表
		unit.current_target = unit.call("select_target")
		return Status.SUCCESS

	var area: Area2D = unit.target_enter_area
	var bodies = area.get_overlapping_bodies()
	if not bodies.is_empty():
		unit.current_target = bodies.pick_random()
		return Status.SUCCESS
		
	# 获取目标组所有成员
	var candidates: Array = unit.get_tree().get_nodes_in_group(unit.target_group)

	# 持续寻找目标
	if candidates.is_empty():
		return Status.RUNNING
		
	# 默认使用随机选择
	if not is_instance_valid(unit.current_target):
		unit.current_target = candidates.pick_random()
		return Status.SUCCESS
	return Status.FAILURE
